<template>
  <view class="image_viewer_root">
    <img
      :src="url"
      :style="{ width: `${100 * scale}%`, left: `${left}px`, top: `${top}px` }"
      class="img"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
      @click="onDblclick"
    />
  </view>
</template>

<script>
export default {
  props: {
    url: {
      type: String,
      default: "https://static-cse.canva.cn/blob/229868/.jpg",
    },
  },
  watch: {
    url() {
      this.left = 0;
      this.top = 0;
      this.scale = 1.5;
    },
  },
  data() {
    return {
      left: 0,
      top: 0,
      scale: 1.5,

      xy: undefined,

      distance: undefined,
    };
  },
  methods: {
    handleTouchMove(event) {
      console.log("event：", event);
      if (event.touches.length == 1) {
        const touches = event.touches[0];
        const xy = { x: touches.clientX, y: touches.clientY };
        if (this.xy) {
          this.left += xy.x - this.xy.x;
          this.top += xy.y - this.xy.y;
        }
        this.xy = xy;
      } else {
        const first = event.touches[0];
        const second = event.touches[1];
        const hypotenuse = this.calculateHypotenuse(first.clientX - second.clientX, first.clientY - second.clientY);
        if (this.distance) {
          this.scale *= hypotenuse / this.distance;
          console.log('scale：', this.scale, hypotenuse, this.distance);
        }
        this.distance = hypotenuse;
      }
    },
    calculateHypotenuse(a, b) {
      return Math.sqrt(a * a + b * b);
    },
    handleTouchEnd() {
      this.xy = undefined;
      this.distance = undefined;
    },
    onDblclick() {
      console.log("onDblclick");
      this.scale += 0.5;
    },
  },
  mounted() { },
  created() { },
};
</script>

<style lang="scss" scoped>
.image_viewer_root {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;

  .img {
    position: absolute;
    object-fit: contain;
  }
}
</style>